package logic

import (
	"context"
	"errors"
	"short-vid-joy/models/cache"
	"short-vid-joy/models/mysql"
	"short-vid-joy/pkg"
	"strings"

	"short-vid-joy/shortrpc/internal/svc"
	"short-vid-joy/shortrpc/shortrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shortrpc.LoginRequest) (*shortrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	if strings.ContainsAny(in.Mobile, "1234567890") == false && len(in.Mobile) != 11 {
		return nil, errors.New("手机号格式错误")
	}

	if err := user.FindUserByMobile(mysql.DB, in.Mobile); err != nil {
		return nil, errors.New("用户不存在")
	}

	if in.LoginType == 1 {
		result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

		if result == "" {
			return nil, errors.New("请发送验证码")
		}

		if in.SmsCode != result {
			return nil, errors.New("验证码错误,请重新输入")
		}
	} else if in.LoginType == 2 {
		if pkg.Md5(in.Password) != user.Password {
			return nil, errors.New("密码错误,请重新输入")
		}

		if user.AccountStatus == 1 {
			return nil, errors.New("账号已禁用，请联系管理员")
		}
	}

	return &shortrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
